package com.wayne.dao.impl;

import com.wayne.dao.AccountDao;
import com.wayne.model.Account;
import com.wayne.utils.ConnectionPool;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

public class AccountDaoImpl implements AccountDao {

  private ConnectionPool connectionPool;

  public void setConnectionPool(ConnectionPool connectionPool) {
    this.connectionPool = connectionPool;
  }

  @Override
  public Account queryAccountByCardNo(String cardNo) throws Exception {
    // 从连接池获取连接
    Connection conn = connectionPool.getCurrentConnection();
    String sql = "select * from t_account where card_no = ?";
    PreparedStatement preparedStatement = conn.prepareStatement(sql);
    preparedStatement.setString(1, cardNo);
    ResultSet resultSet = preparedStatement.executeQuery();
    Account account = new Account();
    while (resultSet.next()) {
      account.setCardNo(resultSet.getString("card_no"));
      account.setName(resultSet.getString("name"));
      account.setMoney(resultSet.getInt("money"));
    }
    resultSet.close();
    preparedStatement.close();
    return account;
  }

  @Override
  public int updateAccountByCardNo(Account account) throws Exception {
    // 从连接池获取连接
    Connection conn = connectionPool.getCurrentConnection();
    String sql = "update t_account set money = ? where card_no = ?";
    PreparedStatement preparedStatement = conn.prepareStatement(sql);
    preparedStatement.setInt(1, account.getMoney());
    preparedStatement.setString(2, account.getCardNo());
    int i = preparedStatement.executeUpdate();
    preparedStatement.close();
    return i;
  }
}
